AddCSLuaFile( "cl_init.lua" );
AddCSLuaFile( "shared.lua" );
include("shared.lua");

function ENT:SpawnFunction( ply, tr )

	if ( !tr.Hit ) then return end
	
	local SpawnPos = ( tr.HitPos + tr.HitNormal * 16 ) + Vector( 0, 0, 32 )
	
	local ent = ents.Create( "ts2_rationdispensa" )
	ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:Activate()
	
	return ent
	
end

function ENT:Initialize()

	self.Entity:SetModel( "models/props_interiors/refrigerator01a.mdl" ); --set fake model
	self.Entity:PhysicsInit( SOLID_VPHYSICS );
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS );
	self.Entity:SetSolid( SOLID_VPHYSICS );
	self.Entity:SetColor( 255, 255, 255, 0 );
	
	local phys = self.Entity:GetPhysicsObject();
	
	if( phys:IsValid() ) then phys:Wake(); end
	
	local spawner = ents.Create( "prop_dynamic" );
	spawner:SetPos(self.Entity:GetPos() - Vector( 0 ,0, 20 ) + self.Entity:GetAngles():Forward() * 2 );
	spawner:SetModel( "models/props_combine/combine_dispenser.mdl" );
	spawner:SetAngles( self.Entity:GetAngles() );
	spawner:Spawn();
	spawner:Activate();
	
	self.Dispenser = spawner
	self.DispenserSeq = self.Dispenser:LookupSequence( "dispense_package" );
	self.Dispenser:SetParent( self.Entity );
	
	self.IsRation = true;
	
end

function ENT:SpawnRation( ply )

	local spawner = self.Dispenser;
	
	if( ply:IsCombineDefense() ) then return end
	
    local attachmentID = spawner:LookupAttachment( "Package_attachment" );      
	local attach = spawner:GetAttachment( attachmentID ); 
	local ent = ents.Create( "ts2_item" );
	ent:AttachItem( "ration" );
	ent:SetSolid( 1 );
	ent:SetParent( spawner );
	ent:Fire( "SetParentAttachment", "Package_attachment" );
	ent:Spawn();
	ent:Activate();
	
	timer.Simple( 2, function() ent:Remove() end );
	
	timer.Simple( 2, function() ply:GiveAnyInventoryItem( "ration" );

		ply:PrintMessage( 3, "You have received a ration from this machine" );

	end );
	
end	

function ENT:Use( activator, caller )

	self.Entity:SetUseType( 3 )

	local spawner = self.Dispenser;
	local trace = activator:GetEyeTrace();
	local pos = self.Entity:WorldToLocal( trace.HitPos );
	self.Entity:WorldToLocal( trace.HitPos );
	
	--[[spawner:Fire( "setanimation", "dispense_package" )
			self:SpawnRation( activator )--]]
			
	if( caller:GetNWBool( "AlreadyGotRation" ) ) then
	
		self.AttemptedUse = true
		activator:PrintMessage( 3, "You already received a ration, check back later." );
		
	else

		spawner:Fire( "setanimation", "dispense_package" );
		self:SpawnRation( activator );
		activator:SetNWBool( "AlreadyGotRation", true );
		
		timer.Simple( 600, function() activator:SetNWBool( "AlreadyGotRation", false ) end ); --errrr~~~ 10mins
		
	end	


end	